package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据用户id查询对应的资源数据
     *
     * @return
     */
    @Override
    public List<MenuVo> getMyMenus() {
        Long userId = ThreadLocalUtil.get();
        //查询数据
        List<MenuVo> menuVoList = resourceMapper.selectMenuByUserId(userId);
        //构建 parentNo -> List<MenuVo> 的映射
        Map<String, List<MenuVo>> parentMap = menuVoList.stream().collect(Collectors.groupingBy(MenuVo::getParentResourceNo));

        //递归构建我的菜单信息
        buildTree(menuVoList, parentMap);
        return parentMap.get(SuperConstant.ROOT_RESOURCE_PARENT_ID);
    }

    /**
     * 资源树形
     *
     * @param dto 资源Dto
     * @return {@code TreeVo }
     * @author YiSheep
     */
    @Override
    public TreeVo resourceTree(ResourceDto dto) {
        String redisKey = "zzyl:resource:tree:vo";
        String redisData = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotBlank(redisData)){
            return JSON.parseObject(redisData, TreeVo.class);
        }
        dto.setResourceType(SuperConstant.MENU);
        dto.setDataState(SuperConstant.DATA_STATE_0); //状态0启用
        List<Resource> resources = resourceMapper.selectList(dto);
        if (CollUtil.isEmpty(resources)) {
            throw new RuntimeException("资源信息未定义");
        }
        Resource rootResource = CollUtil.findOneByField(resources, "parentResourceNo", SuperConstant.ROOT_DEPT_PARENT_ID);
        TreeItemVo treeItemVo = recursionTreeItem(rootResource, resources);
        TreeVo treeVo = TreeVo.builder().items(List.of(treeItemVo)).build();
        stringRedisTemplate.opsForValue().set(redisKey, JSON.toJSONString(treeVo));
        return treeVo;
    }

    /**
     * 资源列表
     *
     * @param dto 资源Dto
     * @return {@code List<ResourceVo> }
     * @author YiSheep
     */
    @Override
    public List<ResourceVo> findResourceList(ResourceDto dto) {
        List<Resource> resources = resourceMapper.selectList(dto);
        List<ResourceVo> resourceVos = BeanUtil.copyToList(resources, ResourceVo.class);
        return resourceVos;
    }

    /**
     * 启用或禁用
     *
     * @param dto 资源Dto
     * @author YiSheep
     */
    @Transactional
    @Override
    public void enableOrDisable(ResourceDto dto) {
        if (StrUtil.equals(dto.getDataState(), SuperConstant.DATA_STATE_0)) {
            Resource parentResource = resourceMapper.selectByResourceNo(dto.getParentResourceNo());
            //判断上一菜单是否启用，如果禁用，则该菜单和该以下菜单都不允许启用
            if (StrUtil.equals(parentResource.getDataState(), SuperConstant.DATA_STATE_1)) {
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }
        resourceMapper.updateByResourceNo(dto.getResourceNo(), dto.getDataState());
        String string = NoProcessing.processString(dto.getResourceNo());
        resourceMapper.updateByParentResourceNo(string, dto.getDataState());
    }

    /**
     * 资源添加
     *
     * @param dto 资源Dto
     * @author YiSheep
     */
    @Override
    public void resourceAdd(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        Resource parentResource = resourceMapper.selectByResourceNo(resource.getParentResourceNo());
        resource.setResourceNo(createResourceNo(resource, parentResource));
        resourceMapper.insert(resource);
    }

    /**
     * 资源修改
     *
     * @param dto 资源Dto
     * @author YiSheep
     */
    @Override
    public void resourceUpdate(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    /**
     * 删除菜单
     *
     * @param menuId 菜单id
     * @author YiSheep
     */
    @Override
    public void resourceDelete(Long menuId) {
        String resourceNo = String.valueOf(menuId);
        Resource resource = resourceMapper.selectByResourceNo(resourceNo);
        if (StrUtil.equals(resource.getDataState(), SuperConstant.DATA_STATE_0)){
            throw new BaseException(BasicEnum.RESOURCE_STATUS_DELETE_ERROR);
        }
        String string = NoProcessing.processString(resourceNo);
        List<Resource> resources = resourceMapper.selectByParentResourceNo(string);
        if (CollUtil.isNotEmpty(resources)) {
            throw new BaseException(BasicEnum.RESOURCE_DELETE_ERROR);
        }
        resourceMapper.deleteByResourceNo(resourceNo);
    }

    /**
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     */
    private String createResourceNo(Resource resource, Resource parentResource) {
        //判断是否是按钮，如果是按钮，则不限制层级
        if (!StrUtil.equals(resource.getResourceType(), SuperConstant.BUTTON)) {
            if (NoProcessing.processString(parentResource.getResourceNo()).length() / 3 >= 5) {
                //判断资源编号是否大于三级
                //100 001 000 000 000
                //100 001 001 000 000
                //100 001 001 001 000
                //100 001 001 001 001 001
                throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
            }
        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResource.getResourceNo()).build();
        List<Resource> resources = resourceMapper.selectList(dto);
        if (ObjectUtil.isEmpty(resources)) {
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResource.getResourceNo(), false);
        } else {
            //有下属节点，在已有的节点上追加，先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(r -> Long.valueOf(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(maxNo), true);
        }
    }

    /**
     * 递归树项
     *
     * @param rootResource 根资源
     * @param resources    资源
     * @return {@code TreeItemVo }
     * @author YiSheep
     */
    private TreeItemVo recursionTreeItem(Resource rootResource, List<Resource> resources) {
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(rootResource.getResourceNo())
                .label(rootResource.getResourceName())
                .build();
        Collection<Resource> childrenResources = CollUtil.filterNew(resources, resource -> StrUtil.equals(resource.getParentResourceNo(), rootResource.getResourceNo()));
        if (CollUtil.isEmpty(childrenResources)) {
            return treeItemVo;
        }
        List<TreeItemVo> treeItemVos = childrenResources.stream().map(resource -> recursionTreeItem(resource, resources)).collect(Collectors.toList());
        treeItemVo.setChildren(treeItemVos);
        return treeItemVo;
    }

    /**
     * 递归构建我的菜单信息（已提供）
     */
    private void buildTree(List<MenuVo> menuVoList, Map<String, List<MenuVo>> parentMap) {
        menuVoList.forEach(menuVo -> {
            //补全数据
            menuVo.setMeta(MenuMetaVo.builder().title(menuVo.getName()).build());
            menuVo.setRedirect("/" + menuVo.getName());
            //根据当前资源编号查询子资源
            List<MenuVo> childrenList = parentMap.get(menuVo.getResourceNo());
            if (CollUtil.isNotEmpty(childrenList)) {
                buildTree(childrenList, parentMap);
                menuVo.setChildren(childrenList);
            }
        });
    }
}
